package com.agent.web;

import com.agent.dto.ActivitiesCreateDTO;
import com.agent.dto.ActivitiesQueryDTO;
import com.agent.dto.ActivitiesUpdateDTO;
import com.agent.entity.Activities;
import com.agent.service.ActivitiesService;
import com.agent.utils.UserContext;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/web/activities")
public class ActivitiesController {

    private final ActivitiesService activitiesService;

    // 获取当天/按条件查询活动列表
    @GetMapping("/list")
    public ResponseEntity<?> list(ActivitiesQueryDTO query,
                                  @RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer size) {
        Map<String, Object> resp = new HashMap<>();
        Long userId = UserContext.getUserId();

        // 创建分页对象
        Page<Activities> pageParam = new Page<>(page, size);

        // 优先用自定义按日期范围方法
        Page<Activities> resultPage;
        // 使用动态查询条件
        LambdaQueryWrapper<Activities> qw = new LambdaQueryWrapper<>();
        qw.eq(Activities::getUserId, userId);
        if (query.getDate() != null) {
            if (query.getStartTime() != null) {
                qw.ge(Activities::getStartTime, query.getStartTime());
            }
            if (query.getEndTime() != null) {
                qw.le(Activities::getEndTime, query.getEndTime());
            }
            qw.orderByAsc(Activities::getDate, Activities::getStartTime);
            resultPage = activitiesService.page(pageParam, qw);
        } else if (query.getWeek() != null) {
            // 按周查询（用通用查询）
            qw
                .eq(Activities::getWeek, query.getWeek())
                .orderByAsc(Activities::getDate, Activities::getStartTime);
            resultPage = activitiesService.page(pageParam, qw);
        } else {
            // 默认返回最近的活动（未来及今天）
            qw
                .ge(Activities::getDate, LocalDate.now())
                .orderByAsc(Activities::getDate, Activities::getStartTime);
            resultPage = activitiesService.page(pageParam, qw);
        }

        resp.put("code", 0);
        resp.put("msg", "ok");
        resp.put("data", resultPage.getRecords());
        resp.put("total", resultPage.getTotal());
        resp.put("current", resultPage.getCurrent());
        resp.put("size", resultPage.getSize());
        resp.put("pages", resultPage.getPages());
        return ResponseEntity.ok(resp);
    }


    // 获取活动详情
    @GetMapping("/detail/{id}")
    public ResponseEntity<?> detail(@PathVariable("id") Long id) {
        Map<String, Object> resp = new HashMap<>();
        Long userId = UserContext.getUserId();
        Activities act = activitiesService.getById(id);
        // 查询当前用户的活动
        if (act == null || !userId.equals(act.getUserId())) {
            resp.put("code", 404);
            resp.put("msg", "Activity not found");
            return ResponseEntity.status(404).body(resp);
        }
        resp.put("code", 0);
        resp.put("msg", "ok");
        resp.put("data", act);
        return ResponseEntity.ok(resp);
    }

    // 创建活动
    @PostMapping("/create")
    public ResponseEntity<?> create(@RequestBody ActivitiesCreateDTO req) {
        Map<String, Object> resp = new HashMap<>();
        Long userId = UserContext.getUserId();
        // 用户需手动提供详情信息
        Activities entity = Activities.builder()
                .userId(userId)
                .activity(req.getActivity())
                .address(req.getAddress())
                .date(req.getDate())
                .startTime(req.getStartTime())
                .endTime(req.getEndTime())
                .allDay(req.getAllDay() == null ? 0 : req.getAllDay())
                .week(req.getWeek())
                .build();

        // 冲突检查
        List<Activities> conflicts = activitiesService.checkConflicts(userId, entity.getDate(), entity.getStartTime(), entity.getEndTime());
        if (!conflicts.isEmpty()){
            resp.put("code", 400);
            resp.put("msg", "Activity conflicts with existing activities");
            return ResponseEntity.badRequest().body(resp);
        }
        // 保存
        boolean ok = activitiesService.save(entity);
        resp.put("code", ok ? 0 : 500);
        resp.put("msg", ok ? "ok" : "create failed");
        resp.put("data", entity.getId());
        return ResponseEntity.ok(resp);
    }

    // 更新活动
    @PutMapping("/update/{id}")
    public ResponseEntity<?> update(@PathVariable("id") Long id, @RequestBody ActivitiesUpdateDTO req) {
        Map<String, Object> resp = new HashMap<>();
        Long userId = UserContext.getUserId();

        Activities act = activitiesService.getById(id);
        if (act == null || !userId.equals(act.getUserId())) {
            resp.put("code", 404);
            resp.put("msg", "Activity not found");
            return ResponseEntity.status(404).body(resp);
        }

        if (req.getActivity() != null) act.setActivity(req.getActivity());
        if (req.getAddress() != null) act.setAddress(req.getAddress());
        if (req.getDate() != null) act.setDate(req.getDate());
        if (req.getStartTime() != null) act.setStartTime(req.getStartTime());
        if (req.getEndTime() != null) act.setEndTime(req.getEndTime());
        if (req.getAllDay() != null) act.setAllDay(req.getAllDay());
        if (req.getWeek() != null) act.setWeek(req.getWeek());

        boolean ok = activitiesService.updateById(act);
        resp.put("code", ok ? 0 : 500);
        resp.put("msg", ok ? "ok" : "update failed");
        return ResponseEntity.ok(resp);
    }

    // 删除活动
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<?> delete(@PathVariable("id") Long id) {
        Map<String, Object> resp = new HashMap<>();
        Long userId = UserContext.getUserId();

        Activities act = activitiesService.getById(id);
        if (act == null || !userId.equals(act.getUserId())) {
            resp.put("code", 404);
            resp.put("msg", "Activity not found");
            return ResponseEntity.status(404).body(resp);
        }

        boolean ok = activitiesService.removeById(id);
        resp.put("code", ok ? 0 : 500);
        resp.put("msg", ok ? "ok" : "delete failed");
        return ResponseEntity.ok(resp);
    }

}
